package gepes.dao;

import gepes.exepcion.DAOExcepcion;
import gepes.modelo.Profesor;
import gepes.modelo.Publicacion;
import gepes.modelo.Usuario;
import gepes.util.ConexionBD;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;

public class UsuarioDAO extends BaseDAO{
	public int login(Usuario us) throws DAOExcepcion{
		String query = "select count(0) from usuario where "
				+ " correo=? and clave=?";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.ConectarDB();
			stmt = con.prepareStatement(query);
			stmt.setString(1, us.getCorreo());
			stmt.setString(2, us.getClave());
			rs = stmt.executeQuery();
			if (rs.next()) {
				return rs.getInt(1);
			}
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {

			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}		
		return 0;
	}
	public Usuario insertar(Usuario us) throws DAOExcepcion {
		
		String query = "insert into usuario(nombre,apepaterno,apematerno,correo,clave)"
				+ "values(?,?,?,?,?)";
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try {
			con = ConexionBD.ConectarDB();
			stmt = con.prepareStatement(query);
			stmt.setString(1, us.getNombre());
			stmt.setString(2, us.getApepaterno());
			stmt.setString(3, us.getApematerno());
			stmt.setString(4,us.getCorreo());
			stmt.setString(5, us.getClave());
			
			int i = stmt.executeUpdate();
			if (i != 1) {
				throw new SQLException("Error insertar");
			}

			int id = 0;
			query = "select last_insert_id()";
			stmt = con.prepareStatement(query);
			rs = stmt.executeQuery();
			if (rs.next()) {
				id = rs.getInt(1);
			}
			us.setCodusuario(id);
			
		} catch (SQLException e) {
			System.err.println(e.getMessage());
			throw new DAOExcepcion(e.getMessage());
		} finally {
			this.cerrarResultSet(rs);
			this.cerrarStatement(stmt);
			this.cerrarConexion(con);
		}
		return us;
	}

}
